import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { ElLoading } from "element-plus";

// export const interfaceUrl = "https://guide-api.library.sh.cn/api/";
export const interfaceUrl = "https://pdlib.zenosh.com/api/";
// export const imgUrl = "https://guide-api.library.sh.cn/";
export const imgUrl = "https://pdlib.zenosh.com/";

export function http({
  url,
  method,
  headers,
  success,
  ...other
}: AxiosRequestConfig & { success?: (res: any) => void }) {
  const loadingInstance = ElLoading.service({
    fullscreen: true,
    background: "rgba(0,0,0,0)",
  });
  return new Promise(
    (resolve: (res: any) => void, reject: (res: any) => void) => {
      axios({
        method: method ? method : "POST", // 默认都是post请求
        url,
        ...other,
        headers: {
          bearer: sessionStorage.getItem("token"),
          ...headers,
        },
      })
        .then((response: AxiosResponse<any>) => {
          const { status, data } = response;
          switch (status) {
            case 200:
              if (data?.code && data.emsg) {
                reject(data);
              } else {
                if (success) {
                  resolve(success(data));
                } else {
                  resolve(data);
                }
              }
              break;
            case 401:
              break;
            default:
              reject(data);
              break;
          }
          loadingInstance.close();
        })
        .catch((error: any) => {
          console.log(error);
          if (!error.response) {
            // router.replace('/');
            return;
          }
          // const { status, data } = error.response;
          // reject(data);
          reject(error);
          loadingInstance.close();
        });
    }
  );
}
